package endoscopic

import (
	"fmt"
	"rongyy/src/app"
	"rongyy/src/middlewares"
	"rongyy/src/models"
)

type OperationType struct {
	models.BaseModel `xorm:"extends"`
	Name             string `xorm:"name" json:"name"`
}

func (pm *OperationType) TableName() string {
	return "operation_type"
}

func (drm *OperationType) Insert() error {
	_, err := app.DB().Insert(drm)
	if err != nil {
		middlewares.Logger.Println("ERROR - OperationType Insert failed ", err)
		return err
	}
	return nil
}

func (pm *OperationType) SelectByName(name string) (*OperationType, error) {
	am := &OperationType{}
	has, err := app.DB().Where("name = ? ", name).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *OperationType) SelectById(id int64) (*OperationType, error) {
	am := &OperationType{}
	has, err := app.DB().Where("id = ? ", id).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *OperationType) Update(req *OperationType) error {
	_, err := app.DB().ID(req.Id).Cols("name").Update(req)
	if err != nil {
		middlewares.Logger.Println("ERROR - type Update failed ", err)
		return fmt.Errorf("更新失败")
	}
	return nil
}

func (ss *OperationType) SelectByList(limit int, start int, name string) ([]OperationType, int64, error) {
	data := make([]OperationType, 0)
	s := app.DB().Table("operation_type")
	if name != "" {
		s.Where("name like ?", "%"+name+"%")
	}
	total, err := s.Limit(limit, limit*start).Desc("created_at").FindAndCount(&data)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}
